<template>
  <div class="detect-upload-container">
    <el-card header="植物病害检测" class="upload-card">
      <!-- 图片上传组件 -->
      <el-upload
          class="upload-area"
          action=""
          :http-request="handleUpload"
          :before-upload="beforeUpload"
          :on-success="onUploadSuccess"
          :on-error="onUploadError"
          :loading="isUploading"
      >
        <el-icon class="upload-icon"><UploadFilled /></el-icon>
        <div class="upload-text">点击或拖拽图片到此处上传</div>
        <div class="upload-hint">支持JPG、PNG格式，大小不超过5MB</div>
      </el-upload>

      <!-- 上传的图片预览 -->
      <div v-if="previewImage" class="image-preview">
        <img :src="previewImage" alt="上传的植物图片" class="preview-img" />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { ElMessage, ElLoading } from 'element-plus';
import { UploadFilled } from '@element-plus/icons-vue';
import request from '@/utils/request';
import { useRouter } from 'vue-router';

const router = useRouter();
const isUploading = ref(false);
const previewImage = ref('');

// 上传前验证（文件类型和大小）
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/');
  if (!isImage) {
    ElMessage.error('只能上传图片文件！');
    return false;
  }
  const isLt5M = file.size / 1024 / 1024 < 5;
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过5MB！');
    return false;
  }
  // 生成预览图
  previewImage.value = URL.createObjectURL(file);
  return true;
};



// 自定义上传逻辑（调用后端接口）
const handleUpload = async (options) => {
  isUploading.value = true;
  const loading = ElLoading.service({ text: '检测中，请稍候...' });

  try {
    // 创建FormData对象（用于上传文件）
    const formData = new FormData();
    formData.append('image', options.file);

    // 调用后端检测接口
    const res = await request.post('/detection/upload', formData, {
      headers: { 'Content-Type': 'multipart/form-data' } // 必须指定类型
    });

    if (res.code === 200) {
      ElMessage.success('检测成功！');
      // 跳转到结果页，携带检测结果参数
      router.push({
        path: '/detect/result',
        query: {
          disease: res.data.diseaseName,
          confidence: res.data.confidence,
          imageUrl: res.data.imageUrl
        }
      });
    } else {
      ElMessage.error(res.message || '检测失败');
    }
  } catch (error) {
    ElMessage.error('网络错误，检测失败');
    console.error(error);
  } finally {
    isUploading.value = false;
    loading.close();
  }
};

const onUploadSuccess = () => {};
const onError = () => {};

// 提交检测（核心对接逻辑）
const submitDetection = async () => {
  if (!selectedFile.value) {
    ElMessage.warning('请先选择图片');
    return;
  }

  isDetecting.value = true;
  const loading = ElLoading.service({ text: '正在检测中，请稍候...' });

  try {
    const formData = new FormData();
    // 键名必须是'image'，与后端upload.single('image')完全一致
    formData.append('image', selectedFile.value);

    // 调用后端检测接口，地址必须与后端路由匹配
    const res = await request.post('/detection/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data' // 必须指定此类型才能上传文件
      }
    });

    if (res.code === 200) {
      ElMessage.success('检测完成！');
      // 跳转到结果页，携带后端返回的参数
      router.push({
        path: '/detect/result',
        query: {
          disease: res.data.diseaseName,
          confidence: res.data.confidence,
          imageUrl: res.data.imageUrl // 后端返回的图片路径（如/uploads/xxx.jpg）
        }
      });
    }
  } catch (error) {
    console.error('检测接口错误：', error);
  } finally {
    isDetecting.value = false;
    loading.close();
  }
};
</script>

<style scoped>
/* 样式略（可根据需求设计） */
</style>